import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    classiyfList: [],
    // 购物车数据
    carList: []
  },
  getters: {
    // 计算总数量
    allCount(state) {
      return state.carList.reduce((next, prev) => {
        if (prev.check) {
          return next + prev.count
        } else {
          return next
        }
      }, 0)
    },
    // 计算总价格
    allPrice(state) {
      return state.carList.reduce((next, prev) => {
        if (prev.check) {
          return next + prev.count * prev.price
        } else {
          return next
        }
      }, 0)
    }
  },
  mutations: {
    setList(state, action) {
      state.classiyfList = action.res
    },
    addCarList(state, action) {
      // state.carList.push(action.item)
      let flag = state.carList.some(item => item.id === action.item.id)
      // 找到carList中的商品
      let index = state.carList.findIndex(item => item.id === action.item.id)
      if (flag) {
        state.carList[index].count += 1
      } else {
        state.carList.push(action.item)
      }
    },
    delCount(state, { index }) {
      state.carList[index].count -= 1
    },
    // 删除其中的某一个
    remItem(state, { index }) {
      state.carList.splice(index, 1)
    },
    // 全选
    allCheckChange(state, { flag }) {
      state.carList.forEach(item => item.check = flag)
    }
  },
  actions: {
    init({ commit }) {
      axios.get('/getList').then(res => {
        commit('setList', {
          res: res.data.list
        })
      })
    }
  },
  modules: {
  }
})
